package rwt.controlpanel;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

/**
 * Manages the system tray icon (appears when the control panel is closed and the Web Server is running).
 */
public class RwtSystemTray implements ActionListener
{
	private TrayIcon trayIcon;
	private SystemTray tray;
	private final JFrame frame;
	
	private boolean isVisible = false;
	
	/**
	 * Constructs a new RwtSystemTray.
	 * @param frame The window frame that the tray icon should make visible when clicked.
	 */
	public RwtSystemTray(JFrame frame)
	{
		this.frame = frame;
		init();
	}
	
	private void init()
	{
		// Check the SystemTray support
		if (!SystemTray.isSupported())
		{
			System.out.println("SystemTray is not supported");
			return;
		}
		
		final PopupMenu popup = new PopupMenu();
		
		// Create a popup menu components
		MenuItem openItem = new MenuItem("Open control panel");
		MenuItem exitItem = new MenuItem("Exit");
		
		// Add components to popup menu
		popup.add(openItem);
		popup.addSeparator();
		popup.add(exitItem);
		
		trayIcon = new TrayIcon(createImage("/images/train.png"), "RWT Web Server", popup);
		trayIcon.setImageAutoSize(true);
		tray = SystemTray.getSystemTray();
		
		trayIcon.addActionListener(this);
		openItem.addActionListener(this);
		
		// Set the exit item's action listener - hides the tray icon and shuts down the control panel application
		exitItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				MainFrame mainFrame = (MainFrame) frame;
				WebServerMonitor monitor = mainFrame.getServerMonitor();
				WebServerController controller = mainFrame.getServerController();
				if (monitor.isRunning())
					controller.stopServer();
				
				hide();
				System.exit(0);
			}
		});
	}
	
	public void displayMessage(String content, TrayIcon.MessageType type)
	{
		trayIcon.displayMessage("RWT Control Panel", content, type);
	}
	
	public void show()
	{
		if (!isVisible)
		{
			isVisible = true;
			try
			{
				tray.add(trayIcon);
			}
			catch (AWTException e)
			{
				System.out.println("TrayIcon could not be added.");
				return;
			}
		}
	}
	
	public void hide()
	{
		tray.remove(trayIcon);
		isVisible = false;
	}
	
	// Obtain the image URL
	protected static Image createImage(String path)
	{
		return new ImageIcon(RwtSystemTray.class.getResource(path)).getImage();
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		frame.setVisible(true);
		hide();
	}
}
